package com.gamota.mobi;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.androidquery.AQuery;
import com.appota.asdk.commons.AccessTokenUtil;
import com.astuetz.viewpager.extensions.PagerSlidingTabStrip;
import com.devspark.appmsg.AppMsg;
import com.gamota.mobi.adapter.ErrorHandler;
import com.gamota.mobi.background.BackgroundTasks;
import com.gamota.mobi.event.Event.ClientUpdateNameNotFoundEvent;
import com.gamota.mobi.event.Event.GetAccessTokenFailEvent;
import com.gamota.mobi.event.Event.GetAccessTokenSuccessEvent;
import com.gamota.mobi.event.Event.LatestVersionEvent;
import com.gamota.mobi.event.Event.RequestFailEvent;
import com.gamota.mobi.event.Event.RequestTokenEvent;
import com.gamota.mobi.fragment.CategoryListFragment;
import com.gamota.mobi.model.AccessToken;
import com.gamota.mobi.model.AppStoreVnUpdateData;
import com.gamota.mobi.network.DownloadUpdateTask;
import com.gamota.mobi.network.IDownloadUpdateCallback;
import com.gamota.mobi.util.Constants;
import com.gamota.mobi.util.RootUtil;
import com.gamota.mobi.util.Utils;
import com.gamota.mobi.view.AlertDialogManager;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;

public class ListingActivity extends SherlockFragmentActivity  implements IDownloadUpdateCallback {
	
	public static final String TOP = "cat_top";
	public static final String KEY_CAT_ID = "_cat_id";
	public static final String KEY_CAT_TITLE = "_cat_title";
	private ViewPager viewPager;
	private String currentStore;
	private Resources res;
	private CategoryFragmentAdapter adapter;
	private int catId;
	private String store;
	private String accessToken;
	private BackgroundTasks bgTask;
	private boolean isRooted;
//	private int indicatorColor;
	private ProgressDialog progressLoading;
	private String updateUri;
	private AQuery aq;
	private String language;
	private boolean notice;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
//		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(R.drawable.actionbar_game_home);
            bg.setTileModeX(TileMode.REPEAT);
            getSupportActionBar().setBackgroundDrawable(bg);
//        }
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_pager);
//		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		initVariables();
		initViews();
		EasyTracker.getInstance().setContext(this);
		Intent i = new Intent(this, NotificationService.class);
		startService(i);
		RootUtil root = new RootUtil();
		isRooted = root.isDeviceRooted();
		((AppStoreVnApplication)getApplication()).setRooted(isRooted);
		PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean(Constants.IS_ROOTED, isRooted).commit();
		notice=getSharedPreferences("Gamota", MODE_PRIVATE).getBoolean("notice", false);
	}
	
	private void setThemeLowEndDevice(int drawableId){
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(drawableId);
            bg.setTileModeX(TileMode.REPEAT);
            getSupportActionBar().setBackgroundDrawable(bg);
        }
	}
	
	private void initVariables(){
		 currentStore = "apps";
		 res = getResources();
		 aq = new AQuery(this);
		 catId = 0;
		 getSupportActionBar().setTitle("GAMOTA");
		 bgTask=new BackgroundTasks(this);
		 progressLoading =new ProgressDialog(this);
		 progressLoading.setCancelable(false);
		 progressLoading.setMessage(getResources().getString(R.string.check_update));
		 progressLoading.show();
		 language= UILApplication.getInstance().getConfig().locale.getLanguage();
		 if(AccessTokenUtil.getInstance().init(this).getSavedAccessToken()!=null && !AccessTokenUtil.getInstance().init(this).getSavedAccessToken().equals("")){
				((AppStoreVnApplication)this.getApplication()).setAccessToken(AccessTokenUtil.getInstance().init(this).getSavedAccessToken());
				accessToken=AccessTokenUtil.getInstance().init(this).getSavedAccessToken();
			}else{
				((AppStoreVnApplication)this.getApplication()).setAccessToken(Constants.DEFIN_TOKEN);
				accessToken=Constants.DEFIN_TOKEN;
			}
		 checkForUpdate();
//		 accessToken=AccessTokenUtil.getInstance().init(this).getSavedAccessToken();
//		 String expired = AccessTokenUtil.getInstance().init(this).getAccessTokenExpires();
//		 if(TextUtils.isEmpty(accessToken)){
//				bgTask.getRequestToken();
//				return;
//			}
//			if(Utils.checkExpired(expired)){
//				bgTask.getRequestToken();
//			}else{
//				progress.dismiss();
//			}
	}
	
	private void initViews(){
		viewPager = (ViewPager) findViewById(R.id.pager);
		DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
		int pageMargin = metrics.widthPixels / 48;
		viewPager.setOffscreenPageLimit(4);
		viewPager.setPageMargin(pageMargin);
		viewPager.setPageMarginDrawable(R.drawable.bg_pagemargin_xml);
		adapter = new CategoryFragmentAdapter(getSupportFragmentManager());
		viewPager.setAdapter(adapter);
		PagerSlidingTabStrip indicator = (PagerSlidingTabStrip) findViewById(R.id.indicator);
        indicator.setViewPager(viewPager);
        int pixelSize = (int) (14 * metrics.scaledDensity); 
        indicator.setTextSize(pixelSize);
//        indicator.setTabBackground(R.drawable.tabtext_bg);
        indicator.setIndicatorColorResource(R.color.app_indicator);//indicator.setIndicatorColor(Color.BLUE);
        indicator.setUnderlineColorResource(R.color.app_indicator);
        indicator.setTextColor(Color.WHITE);
	}
	
	@Override
	protected void onResume() {
		if(language.equals(UILApplication.getInstance().getConfig().locale.getLanguage())){
			super.onResume();
		}else{
			super.onResume();
			initViews();
			language= UILApplication.getInstance().getConfig().locale.getLanguage();
		}
		com.facebook.AppEventsLogger.activateApp(this, getResources().getString(R.string.fb_app_id));
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getSupportMenuInflater().inflate(R.menu.activity_search_result, menu);
		View v = (View) menu.findItem(R.id.search).getActionView();
    	final AutoCompleteTextView txtSearch = (AutoCompleteTextView) v.findViewById(R.id.text_search);
    	txtSearch.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
		        	if(!TextUtils.isEmpty(aq.id(R.id.text_search).getText().toString())){
		        		EditText keySearch=aq.id(R.id.text_search).getEditText();
//		        		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//						imm.hideSoftInputFromWindow(keySearch.getWindowToken(), 0);
		        		startSearch(txtSearch.getText().toString());
		        		txtSearch.setText("");
		        		txtSearch.clearFocus();
			            return true;
		        	} else {
		        		Toast.makeText(ListingActivity.this, R.string.input_search, Toast.LENGTH_SHORT).show();
		        		return true;
		        	}
		        }
		        return false;
			}
		});
    	ImageButton btn_search=(ImageButton)v.findViewById(R.id.btn_search);
    	btn_search.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
		        	if(!TextUtils.isEmpty(aq.id(R.id.text_search).getText().toString())){
		        		EditText keySearch=aq.id(R.id.text_search).getEditText();
		        		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(keySearch.getWindowToken(), 0);
		        		startSearch(keySearch.getText().toString());
		        		txtSearch.clearFocus();
		        		txtSearch.setText("");
		        	} else {
		        		Toast.makeText(ListingActivity.this, R.string.input_search, Toast.LENGTH_SHORT).show();
		        	}
			}
		});
		return super.onCreateOptionsMenu(menu);
	}

	private void startSearch(String query) {
		Log.e("start", "start search");
		EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.SEARCH_EVENT_ACTION, "search keyword: " + query, Long.valueOf(1));
		Intent intent = new Intent(ListingActivity.this, SearchResultActivity.class);
		intent.putExtra(Constants.SEARCH_QUERY, query);
		intent.putExtra(Constants.STORE_KEY, "");
		startActivity(intent);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		case R.id.menu_search:
			EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.EVENT_ACTION, "search-button", Long.valueOf(10));
			Intent search = new Intent(this, SearchActivity.class);
			search.putExtra(Constants.SEARCH_TYPE, store);
			startActivity(search);
			return true;
		case R.id.menu_account:
			EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.EVENT_ACTION, "menu-account", Long.valueOf(1));
			boolean isLogin = Utils.getStaticIsLogin(this);
//			if (isLogin) {
//				Intent account = new Intent(ListingActivity.this, AccountActivity.class);
//				startActivity(account);
//			} else {
//				Intent login = new Intent(ListingActivity.this, LoginActivity.class);
//				startActivity(login);
//			}
			return true;
		case R.id.menu_manage:
			EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.EVENT_ACTION, "menu-manage", Long.valueOf(1));
			Intent i = new Intent(ListingActivity.this, AppManageActivity.class);
			i.putExtra(Constants.STORE_KEY, store);
			startActivity(i);
			return true;
		case R.id.menu_setting:
			EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.EVENT_ACTION, "menu-setting", Long.valueOf(1));
			Intent setting = new Intent(ListingActivity.this, SettingsActivity.class);
			startActivity(setting);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		//EasyTracker.getInstance().activityStop(this);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EasyTracker.getInstance().activityStart(this);
		EventBus.getDefault().unregister(this);
		EventBus.getDefault().register(this);
	}
	@Override
	protected void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}
	@Override
	public void onBackPressed() {
		showNoticeRate();
	}
	private void showNoticeRate() {
		
		if(!notice){
			AlertDialog.Builder builder=new Builder(this);
			builder.setMessage(getResources().getString(R.string.noticerate)).setNegativeButton(getResources().getString(R.string.close), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			}).setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					getSharedPreferences("Gamota", MODE_PRIVATE).edit().putBoolean("notice", true).commit();
					startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.gamota.mobi")));
				    finish();
				}
			}).show();
		}else{
			finish();
		}
	}
	private class CategoryFragmentAdapter extends FragmentStatePagerAdapter {
		
		protected String[] TITLE = new String[] { res.getString(R.string._free),res.getString(R.string._new), res.getString(R.string._hot)};

		public CategoryFragmentAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int pos) {
			CategoryListFragment frag = new CategoryListFragment();
			Bundle bundle = new Bundle();
			String top = "";
			if(TITLE[pos].contains(getResources().getString(R.string._new))){
				top="Newest";
			}else if(TITLE[pos].contains(getResources().getString(R.string._free))){
				top="Top Free";
			}else{
				top="Hot";
			}
			bundle.putString(Constants.TOP, top);
			bundle.putInt(Constants.CATEGORY_ID, catId);
			bundle.putString(Constants.STORE_KEY, currentStore);
			frag.setArguments(bundle);
			return frag;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return TITLE.length;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			// TODO Auto-generated method stub
			return TITLE[position];
		}
		
		@Override
		public void setPrimaryItem(ViewGroup container, int position, Object object) {
			// TODO Auto-generated method stub
			if(position > 0){
				CategoryListFragment frag = (CategoryListFragment) object;
				frag.init();
			}
		}
	}
	public static class InstalledAppItem {
		public String getPackageName() {
			return packageName;
		}
		public String getVersion() {
			return version;
		}
		private String packageName;
		private String version;
		public InstalledAppItem(String packageName, String version) {
			this.packageName = packageName;
			this.version = version;
		}
		
	}
	public void onEventMainThread(GetAccessTokenFailEvent event){
		if(event.getErrorCode() == -2){
			PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean(Constants.LOGIN, false).commit();
			bgTask.getRequestToken();
		} else {
			ErrorHandler.getInstance().setContext(this).handleError(event.getErrorCode());
		}
	}
	
	public void onEventMainThread(RequestFailEvent event){
		if(event.getErrorCode() == -101){
			AlertDialogManager am = new AlertDialogManager(this);
			am.showPositiveDialog(R.string.no_internet, R.string.retry, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					checkForUpdate();
				}
			});
		}else if(event.getErrorCode() ==401){
			bgTask.getRequestToken();
		}
		else {
			AlertDialogManager am = new AlertDialogManager(this);
			am.showPositiveDialog(R.string.error, R.string.retry, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					checkForUpdate();
				}
			});
		}
	}
	
	private void checkForUpdate(){
		String deviceStatus;
		if(isRooted){
			deviceStatus = "1";
		} else {
			deviceStatus = "0";
		}
		bgTask.checkClientUpdate(deviceStatus);
	}
	
	public void onEventMainThread(RequestTokenEvent event){
		if(TextUtils.isEmpty(event.getRequestToken())){
			AppMsg.makeText(this, R.string.error, AppMsg.STYLE_ALERT, null).show();
		} else {
			bgTask.getAccessToken(event.getRequestToken());
		}
	}
	
	public void onEventMainThread(GetAccessTokenSuccessEvent event){
		if(progressLoading!=null && progressLoading.isShowing()){
			progressLoading.dismiss();
		}
		AccessToken accessToken = event.getAt();
		((AppStoreVnApplication) getApplication()).setAccessToken(accessToken.getAccessToken());
		((AppStoreVnApplication) getApplication()).setCountryCode(accessToken.getCountryCode());
//		UILApplication.getInstance().saveStaticAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn());
		AccessTokenUtil.getInstance().init(this).saveAccessTokenStr(accessToken.getAccessToken());
		AccessTokenUtil.getInstance().init(this).saveAccessTokenExpires(accessToken.getExpiresIn());
//		UILApplication.getInstance().saveStaticAccessToken(accessToken.getAccessToken(), accessToken.getExpiresIn());
		Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
		editor.putString(Constants.REFRESH_TOKEN, accessToken.getRefreshToken());
		editor.commit();
		
	}
	
	public boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

		return cm.getActiveNetworkInfo() != null
				&& cm.getActiveNetworkInfo().isConnectedOrConnecting();
	}
	
	public void onEventMainThread(ClientUpdateNameNotFoundEvent event){
		if(progressLoading!=null && progressLoading.isShowing()){
			progressLoading.dismiss();
		}
	}
	
	public void onEventMainThread(LatestVersionEvent event){
		Log.e("latest","latest");
//		Toast.makeText(this, "Country: "+event.getCountryCode(), Toast.LENGTH_LONG).show();
//		PreferenceManager.getDefaultSharedPreferences(this).edit().putString(Constants.COUNTRY_CODE, event.getCountryCode()).commit();//event.getCountryCode()
		if(progressLoading!=null && progressLoading.isShowing()){
			progressLoading.dismiss();
		}
		progressLoading.setMessage(getResources().getString(R.string.loading));
	}
	public void onEventMainThread(AppStoreVnUpdateData data){
		if(progressLoading!=null && progressLoading.isShowing()){
			progressLoading.dismiss();
		}
		progressLoading.setMessage(getResources().getString(R.string.loading));
		updateUri = data.getUpdateUrl();
//		PreferenceManager.getDefaultSharedPreferences(this).edit().putString(Constants.COUNTRY_CODE, data.getCountryCode()).commit();//putString(Constants.COUNTRY_CODE, data.getCountryCode()).commit();//putString(Constants.COUNTRY_CODE, "vn").commit();
		if(updateUri.startsWith("market")){
			if(data.isForce()){
				try {
				    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(updateUri)));
				    finish();
				} catch (android.content.ActivityNotFoundException anfe) {
				}
			} else {
				Intent showUpdate = new Intent(this, PopupUpdateActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable(Constants.KEY_UPDATE_DATA, data);
				showUpdate.putExtras(bundle);
				startActivityForResult(showUpdate, REQUEST_CODE);
			}
		} else {
			if(data.isForce()){
					DownloadUpdateTask task = new DownloadUpdateTask(this);
					task.setDownloadCallback(this);
					task.execute(updateUri);
			} else {
				Intent showUpdate = new Intent(this, PopupUpdateActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable(Constants.KEY_UPDATE_DATA, data);
				showUpdate.putExtras(bundle);
				startActivityForResult(showUpdate, REQUEST_CODE);
			}
		}
		
	}
	public static final int REQUEST_CODE = 99;
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if(requestCode == REQUEST_CODE && resultCode == RESULT_OK){
			if(updateUri.startsWith("market")){
				try {
				    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(updateUri)));
				} catch (android.content.ActivityNotFoundException anfe) {
				}
			}else{
				DownloadUpdateTask task = new DownloadUpdateTask(ListingActivity.this);
				task.setDownloadCallback(this);
				task.execute(updateUri);
			}
			
		} 
	}

	@Override
	public void onDownloadComplete(String path) {
		// TODO Auto-generated method stub
		Utils.installAPK(this, path);
		finish();
	}

	@Override
	public void onDownloadError() {
		// TODO Auto-generated method stub
		
	}
}
